﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using System.Text.RegularExpressions;
using System.Web.UI.HtmlControls;

namespace Framework.WebmasterTool.Advertisings
{
    public partial class Default : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();

        public string GridViewSortExpression
        {
            get { return ViewState["GridViewSortExpression"] == null ? "AddedDate" : ViewState["GridViewSortExpression"] as string; }
            set { ViewState["GridViewSortExpression"] = value; }
        }

        public SortDirection GridViewSortOrder
        {
            get { return ViewState["GridViewSortOrder"] == null ? SortDirection.Descending : (SortDirection)ViewState["GridViewSortOrder"]; }
            set { ViewState["GridViewSortOrder"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CheckPermission();
                LoadAdvertisings();
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.Advertising.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        public void LoadAdvertisings()
        {
            var advertisings = entity.udv_Advertise.Select(ad => new { ad.AdvID, ad.AdvName, ad.CustomerName, ad.AddedDate, ad.ReleaseDate, ad.ExpireDate, ad.IsActive, ad.DisplayOrder }).ToList();
            if (GridViewSortOrder.Equals(SortDirection.Ascending))
                advertisings = advertisings.OrderBy(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            else
                advertisings = advertisings.OrderByDescending(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            grvAdvertising.DataSource = advertisings;
            grvAdvertising.DataBind();
        }

        public void SearchAdvertising()
        {
            var advertisings = entity.udv_Advertise.Select(ad => new { ad.AdvID, ad.AdvName, ad.CustomerName, ad.AddedDate, ad.ReleaseDate, ad.ExpireDate, ad.IsActive, ad.DisplayOrder }).ToList();
            if (txtKeyword.Text.Trim() != "")
            {
                string keyword = Globals.RemoveSign4VietnameseString(txtKeyword.Text.Trim().ToLower());
                advertisings = advertisings.Where(ad => Globals.RemoveSign4VietnameseString(ad.AdvName).ToLower().Contains(keyword) || Globals.RemoveSign4VietnameseString(ad.CustomerName).ToLower().Contains(keyword) || ad.AddedDate.Value.ToString("dd/MM/yyyy").Contains(keyword) || ad.ReleaseDate.Value.ToString("dd/MM/yyyy").Contains(keyword) || ad.ExpireDate.Value.ToString("dd/MM/yyyy").Contains(keyword)).ToList();
            }
            if (GridViewSortOrder.Equals(SortDirection.Ascending))
                advertisings = advertisings.OrderBy(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            else
                advertisings = advertisings.OrderByDescending(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            grvAdvertising.DataSource = advertisings;
            grvAdvertising.DataBind();
        }

        protected void grvAdvertising_Sorting(object sender, GridViewSortEventArgs e)
        {
            //Check if the same column is sorted to switch Sort Order  
            if (GridViewSortExpression.Equals(e.SortExpression))
                GridViewSortOrder = GridViewSortOrder.Equals(SortDirection.Ascending) ? SortDirection.Descending : SortDirection.Ascending;
            else
                GridViewSortOrder = SortDirection.Ascending;
            //save Sort Expression and Sort Order
            GridViewSortExpression = e.SortExpression;
            if (grvAdvertising.ToolTip == "all")
                LoadAdvertisings();
            else
            {
                SearchAdvertising();
            }
        }

        protected void grvAdvertising_DataBinding(object sender, EventArgs e)
        {
            string srcImageASC = Globals.ApplicationPath + "WebmasterTool/Images/ASC.gif";
            string srcImageDESC = Globals.ApplicationPath + "WebmasterTool/Images/DESC.gif";
            foreach (DataControlField column in grvAdvertising.Columns)
            {
                //Remove Previous Sort Image  
                column.HeaderText = Regex.Replace(column.HeaderText, "<[^>]*>", "", RegexOptions.IgnoreCase);
                if (column.SortExpression.Equals(GridViewSortExpression))
                {
                    //set new sort image  
                    string strSortImageURL = GridViewSortOrder == SortDirection.Descending ?
                                            "<img border='0' style='background-color:White;vertical-align:middle;' src='" + srcImageDESC + "' />" :
                                            "<img border='0' style='background-color:White;vertical-align:middle;' src='" + srcImageASC + "' />";
                    column.HeaderText = String.Format("{0}{1}", column.HeaderText, strSortImageURL);
                }
            }
        }

        protected void grvAdvertising_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvAdvertising.PageIndex = e.NewPageIndex;
            if (grvAdvertising.ToolTip == "all")
                LoadAdvertisings();
            else
            {
                SearchAdvertising();
            }
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            Response.Redirect("AdvertisingAdd.aspx");
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            grvAdvertising.PageIndex = 0;
            grvAdvertising.ToolTip = "search";
            SearchAdvertising();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in grvAdvertising.Rows)
            {
                bool isChecked = ((HtmlInputCheckBox)row.FindControl("chkSelect")).Checked;
                if (isChecked)
                {
                    int advertisingID = int.Parse(((HtmlInputCheckBox)row.FindControl("chkSelect")).Attributes["title"].Trim());
                    udv_Advertise advertisingDelete = entity.udv_Advertise.Where(ad => ad.AdvID == advertisingID).FirstOrDefault();
                    if (advertisingDelete != null)
                    {
                        Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_Advertisings_Folder_MapPath + advertisingDelete.AdvURL));
                        //create db log
                        CreateDBLog(null, null, TypeAction.Delete, "Xoá quảng cáo: " + advertisingDelete.AdvName + " - " + advertisingDelete.CustomerName, "", "", advertisingDelete.ReleaseDate != null ? string.Format("{0:dd/MM/yyyy HH:mm:ss}", advertisingDelete.ReleaseDate) : "", advertisingDelete.ExpireDate != null ? string.Format("{0:dd/MM/yyyy HH:mm:ss}", advertisingDelete.ExpireDate) : "",
                            advertisingDelete.IsActive.Value.ToString(), "", "", "");
                        entity.DeleteObject(advertisingDelete);
                        entity.SaveChanges();
                    }
                }
            }
            if (grvAdvertising.ToolTip == "all")
                LoadAdvertisings();
            else
            {
                SearchAdvertising();
            }
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}